package com.jnc.web.biz.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.jnc.common.constant.SysConstant;
import com.jnc.common.exception.BaseException;
import com.jnc.common.util.convert.ConvertUtil;
import com.jnc.core.base.model.Role;
import com.jnc.core.base.service.RoleService;
import com.jnc.web.biz.system.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @Author: jjn
 * @Date: 2018/9/19
 * @Desc:
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Role> queryRole(Role record) {
        return roleMapper.queryRole(record);
    }

    @Override
    public Role getRole(Integer roleId) {
        return roleMapper.getRole(roleId);
    }

    @Override
    public List<Role> checkRole(Role record) {
        return roleMapper.checkRole(record);
    }

    @Transactional(value = SysConstant.TX_BASE_NAME)
    @Override
    public int deleteRole(String ids) {
        List<Integer> list = ConvertUtil.toIntList(ids);
        Integer count = roleMapper.deleteRole(list);
        //删除关联表数据
        deleteForeignKey(list);
        return count;
    }

    @Transactional(value = SysConstant.TX_BASE_NAME)
    @Override
    public int addRole(Role record) {
        return roleMapper.addRole(record);
    }

    @Transactional(value = SysConstant.TX_BASE_NAME)
    @Override
    public int editRole(Role record) {
        return roleMapper.editRole(record);
    }

    @Override
    public List<String> getRoleCodeByUser(Integer userId) {
        return roleMapper.getRoleCodeByUser(userId);
    }

    @Transactional(value = SysConstant.TX_BASE_NAME)
    @Override
    public int author(Role role) {
        if(null == role || role.getRoleId() == null){
            throw new BaseException("角色或角色ID为空");
        }
        //先删除该角色的授权菜单信息
        List<Integer> roleList = CollectionUtil.newArrayList();
        roleList.add(role.getRoleId());
        roleMapper.deleteRoleMenu(roleList);
        //新增该角色的授权菜单信息
        Map<String, Object> map = MapUtil.newHashMap();
        map.put("roleId", role.getRoleId());
        map.put("menuIds", ConvertUtil.toIntList(role.getMenuIds()));
        return roleMapper.addRoleMenu(map);
    }

    /**
     * 删除关联表数据
     * @param roleIds
     */
    private void deleteForeignKey(List<Integer> roleIds){
        roleMapper.deleteUserRole(roleIds);
        roleMapper.deleteRoleMenu(roleIds);
    }

}
